﻿using System.Windows;

namespace HobSoft.SoccerBet2014.Common.Wpf.Behavior
{
    public static class FocusExtension
    {
        public static bool GetIsFocused(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsFocusedProperty);
        }

        public static void SetIsFocused(DependencyObject obj, bool value)
        {
            var uie = (UIElement)obj;
            uie.SetValue(IsFocusedProperty, value);
        }

        public static readonly DependencyProperty IsFocusedProperty =
                DependencyProperty.RegisterAttached(
                 "IsFocused", typeof(bool), typeof(FocusExtension),
                 new UIPropertyMetadata(false, OnIsFocusedPropertyChanged));

        private static void OnIsFocusedPropertyChanged(DependencyObject d,
                DependencyPropertyChangedEventArgs e)
        {
            var uie = (UIElement)d;
            if ((bool)e.NewValue)
            {
                uie.Focus();
                uie.LostFocus += uie_LostFocus;
            }
        }

        static void uie_LostFocus(object sender, RoutedEventArgs e)
        {
            var uie = (UIElement)sender;
            uie.SetValue(IsFocusedProperty, false);
            uie.LostFocus -= uie_LostFocus;
        }
    }
}
